package com.xebest.web.controller.aftersales;

import com.github.pagehelper.PageHelper;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.erp.aftersales.VenAfterSaleSourceEnum;
import com.xebest.common.enums.erp.aftersales.VenAfterSaleStatusEnum;
import com.xebest.common.enums.erp.aftersales.VenAfterSaleTypeEnum;
import com.xebest.common.enums.erp.order.VenOrderStatusEnum;
import com.xebest.common.enums.erp.sys.VenDelEnum;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.RequestUtil;
import com.xebest.config.ParamConfig;
import com.xebest.constant.XeConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.Money;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.msg.XeVenAfterSaleMsg;
import com.xebest.util.seq.FinanceSeqUtil;
import com.xebest.web.form.*;
import com.xebest.web.model.XeVenAfterSaleDetailEntity;
import com.xebest.web.model.XeVenAfterSaleEntity;
import com.xebest.web.model.XeVenOrderInfoDetailEntity;
import com.xebest.web.model.XeVenOrderInfoEntity;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenAfterSaleService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.view.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenjing
 */
@RestController
@RequestMapping("afterSales")
@Scope("prototype")
public class XeVenAfterSaleController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(XeVenAfterSaleController.class);//日志记录类
    @Autowired
    private XeVenAfterSaleService xeVenAfterSaleService;
    @Autowired
    private FinanceSeqUtil financeSeqUtil;
    @Autowired
    private XeVenOrderService xeVenOrderService;
    @Autowired
    private ParamConfig paramConfig;

    /**
     * 查询售后单列表
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryAfterSaleList", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse queryAfterSaleList(@RequestBody XeVenAfterSaleQueryForm form) {
        log.info("查询售后单列表:{}", ToStringBuilder.reflectionToString(form));
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        if (null == form) {
            form = new XeVenAfterSaleQueryForm();
        }
        form.setUserCode(userInfo.getUserCode());
        String createStartDate = form.getCreateStartDate();
        String createEndDate = form.getCreateEndDate();
        //设定查询中日期为3个月以内
        if (StringUtils.isNotBlank(createStartDate) && StringUtils.isNotBlank(createEndDate)) {
            Boolean dateCm = DateUtil.comparableTime(createStartDate, createEndDate);
            if (!dateCm) {
                return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_DATE_COMPARABLE);
            }
        }
        if (StringUtils.isBlank(createStartDate) && StringUtils.isBlank(createEndDate)) {
            createEndDate = DateUtil.getDate(new Date());
            ;
            createStartDate = DateUtil.strToNMonth(createEndDate, -3);
        }
        if (StringUtils.isBlank(createStartDate) && StringUtils.isNotBlank(createEndDate)) {
            form.setCreateStartDate(DateUtil.strToNMonth(createEndDate, -3));
        }
        if (StringUtils.isBlank(createEndDate) && StringUtils.isNotBlank(createStartDate)) {
            form.setCreateEndDate(DateUtil.strToNMonth(createStartDate, 3));
        }
        if (StringUtils.isNotBlank(form.getFormIdType())) {
            int formIdType = Integer.parseInt(form.getFormIdType());
            switch (formIdType) {
                case 1:   //售后单号
                    form.setAfterSalesCode(form.getFormIdValue());
                    break;
                case 2:   //订单编号,
                    form.setOrderInfo(form.getFormIdValue());
                    break;
                case 3:   //商品名称
                    form.setProName(form.getFormIdValue());
                    break;
                case 4:   //商品货号
                    form.setProNum(form.getFormIdValue());
                    break;
                case 5:   //客户账号
                    form.setUserId(form.getFormIdValue());
                    break;
                case 6:   // 收货人
                    form.setCaConsignee(form.getFormIdValue());
                    break;
                default:
                    break;
            }

        }
        XePageInfo<XeVenAfterSaleView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        try {
            //售后单列表
            List<XeVenAfterSaleView> afterSaleViewList = xeVenAfterSaleService.queryAfterSaleList(form);
            xePageInfo = new XePageInfo<>(afterSaleViewList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("afterSaleViewList", afterSaleViewList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================查询售后单列表异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 售后单作废
     *
     * @author chenjing
     */
    @RequestMapping(value = "cancelAfterSale", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse cancelAfterSale(@RequestBody XeVenAfterSaleDetailForm form) {
        log.info("售后单作废入参:{}", ToStringBuilder.reflectionToString(form));

        if (null == form) return sendAjaxError(BASEMessage.PARAM_ERROR);
        String afterSaleCode = form.getAfterSalesCode();
        if (StringUtils.isBlank(afterSaleCode) || StringUtils.isBlank(form.getRefusReason())) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        XeVenAfterSaleEntity entity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userInfo.getUserCode());
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //如果售后单已审核 不允许作废
        if (VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }

        try {
            entity.setUserCode(userInfo.getUserCode());
            entity.setModifyUser(userInfo.getUserName());
            entity.setAfterSaleStatus(VenAfterSaleStatusEnum.CANCELED.getValue());
            entity.setCancelReason(form.getRefusReason());
            entity.setCancelUser(userInfo.getUserName());
            int flag = xeVenAfterSaleService.cancelAfterSale(entity);
            if (flag > 0) {
                //插入日志信息
                String operatorContent = "作废售后单:" + afterSaleCode + ",作废原因:" + form.getRefusReason();
                insertMqLog("", afterSaleCode, operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.info("================作废售后单异常======================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 批量作废售后单(已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "cancelAfterSaleList", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse cancelAfterSaleList(@RequestBody @Validated XeVenAfterSaleDelForm form,
                                     BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单批量作废缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String[] formCodes = form.getAfterSaleFormCodes();
        if (formCodes.length == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        form.setAfterSaleFormCodes(formCodes);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setModifyUser(userInfo.getUserName());
        form.setUserCode(userCode);
        /**
         * 批量作废售后单时，代码中未作状态验证，在sql中直接筛选掉状态=已审核过的数据
         */
        try {
            int flag = xeVenAfterSaleService.cancelAfterSaleList(form);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.error("================批量删除售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 删除售后单 （已弃用）
     *
     * @author chenjing
     */
    @RequestMapping(value = "delAfterSale", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse deleteByAfterSalesCode(@RequestBody XeVenAfterSaleDetailForm form) {
        if (null == form) return sendAjaxError(BASEMessage.PARAM_ERROR);
        String afterSaleCode = form.getAfterSalesCode();
        if (StringUtils.isBlank(afterSaleCode)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        log.info("删除售后单,售后单号={},userCode={}", afterSaleCode, userInfo.getUserCode());
        XeVenAfterSaleEntity entity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userInfo.getUserCode());
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //如果售后单已审核 不允许删除
        if (VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }
        try {
            entity.setUserCode(userInfo.getUserCode());
            entity.setModifyUser(userInfo.getUserName());
            int flag = xeVenAfterSaleService.deleteByAfterSalesCode(entity);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.info("================删除售后单异常======================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 客服审核售后单
     *
     * @author chenjing
     */
    @RequestMapping(value = "batchAfterSaleByService", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse batchAfterSaleByService(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                         BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单客服审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String operatorContent = "";               //记录日志信息
        String afterSaleCode = form.getFormCode();  //售后单号
        int checkStatus = form.getCheckStatus();  //审核状态
        String refusReason = form.getRefusReason();  //驳回原因
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus) && StringUtils.isBlank(refusReason)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        XeVenAfterSaleEntity entity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (!VenAfterSaleStatusEnum.PENDING.getValue().equals(entity.getServiceCheckStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_BACKED);
        }
        if (VenAfterSaleStatusEnum.CANCELED.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_CANCELED);
        }
        //如果客服审核通过，采购已审核通过，财务审核也通过，则更新售后单审核状态为已通过
        if (VenAfterSaleStatusEnum.PASS.getValue().equals(checkStatus)) {
            if (VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getPurchaseCheckStatus())
                    && VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getFinanceCheckStatus())) {
                entity.setAfterSaleStatus(VenAfterSaleStatusEnum.PASS.getValue());
                operatorContent = "客服审核通过售后单：" + afterSaleCode + ",售后单审核全部通过";
            } else {
                entity.setAfterSaleStatus(VenAfterSaleStatusEnum.CHECKING.getValue());
                operatorContent = "客服审核通过售后单：" + afterSaleCode;
            }
        }

        //如果为审核不通过，则更新售后单状态为驳回
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus)) {
            entity.setAfterSaleStatus(VenAfterSaleStatusEnum.BACKED.getValue());
            entity.setRefusUser(userInfo.getUserName());
            operatorContent = "客服审核驳回售后单：" + afterSaleCode + ",驳回原因：" + refusReason;
        }
        entity.setModifyUser(userInfo.getUserName());
        entity.setServiceCheckStatus(checkStatus); //审核状态 2=通过 3=不通过
        entity.setRefusReason(refusReason);   //审核驳回原因
        entity.setUserCode(userCode);


        try {
            int flag = xeVenAfterSaleService.updateByPrimaryKey(entity);
            if (flag > 0) {
                //插入日志信息
                insertMqLog("", afterSaleCode, operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================客服审核售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 采购审核售后单
     *
     * @author chenjing
     */
    @RequestMapping(value = "batchAfterSaleByPurchase", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse batchAfterSaleByPurchase(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                          BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单采购审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String operatorContent = "";               //记录日志信息
        String afterSaleCode = form.getFormCode();  //售后单号
        int checkStatus = form.getCheckStatus();  //审核状态
        String refusReason = form.getRefusReason();  //驳回原因
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus) && StringUtils.isBlank(refusReason)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        XeVenAfterSaleEntity entity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (!VenAfterSaleStatusEnum.PENDING.getValue().equals(entity.getPurchaseCheckStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_BACKED);
        }
        if (VenAfterSaleStatusEnum.CANCELED.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_CANCELED);
        }
        //如果客服审核通过，采购已审核通过，财务审核也通过，则更新售后单审核状态为已通过
        if (VenAfterSaleStatusEnum.PASS.getValue().equals(checkStatus)) {
            if (VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getServiceCheckStatus())
                    && VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getFinanceCheckStatus())) {
                entity.setAfterSaleStatus(VenAfterSaleStatusEnum.PASS.getValue());
                operatorContent = "采购审核通过售后单：" + afterSaleCode + ",售后单审核全部通过";
            } else {
                entity.setAfterSaleStatus(VenAfterSaleStatusEnum.CHECKING.getValue());
                operatorContent = "采购审核通过售后单：" + afterSaleCode;
            }
        }

        //如果为审核不通过，则更新售后单状态为驳回
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus)) {
            entity.setAfterSaleStatus(VenAfterSaleStatusEnum.BACKED.getValue());
            entity.setRefusUser(userInfo.getUserName());
            operatorContent = "采购审核驳回售后单：" + afterSaleCode + ",驳回原因：" + refusReason;
        }
        entity.setModifyUser(userInfo.getUserName());
        entity.setPurchaseCheckStatus(checkStatus); //审核状态 2=通过 3=不通过
        entity.setRefusReason(refusReason);   //审核驳回原因
        entity.setUserCode(userCode);

        try {
            int flag = xeVenAfterSaleService.updateByPrimaryKey(entity);
            if (flag > 0) {
                //插入日志信息
                insertMqLog("", afterSaleCode, operatorContent);
                return sendAjaxOK();
            } else {
                return sendAjaxError();
            }
        } catch (Exception e) {
            log.error("================采购审核售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 财务审核售后单
     *
     * @author chenjing
     */
    @RequestMapping(value = "batchAfterSaleByFinance", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse batchAfterSaleByFinance(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                         BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单财务审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String operatorContent = "";               //记录日志信息
        String afterSaleCode = form.getFormCode();  //售后单号
        int checkStatus = form.getCheckStatus();  //审核状态
        String refusReason = form.getRefusReason();  //驳回原因
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus) && StringUtils.isBlank(refusReason)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        XeVenAfterSaleEntity entity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (!VenAfterSaleStatusEnum.PENDING.getValue().equals(entity.getFinanceCheckStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_BACKED);
        }
        if (VenAfterSaleStatusEnum.CANCELED.getValue().equals(entity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_CANCELED);
        }
        //如果客服审核通过，采购已审核通过，财务审核也通过，则更新售后单审核状态为已通过
        if (VenAfterSaleStatusEnum.PASS.getValue().equals(checkStatus)) {
            if (VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getServiceCheckStatus())
                    && VenAfterSaleStatusEnum.PASS.getValue().equals(entity.getPurchaseCheckStatus())) {
                entity.setAfterSaleStatus(VenAfterSaleStatusEnum.PASS.getValue());
                operatorContent = "财务审核通过售后单：" + afterSaleCode + ",售后单审核全部通过";
            } else {
                entity.setAfterSaleStatus(VenAfterSaleStatusEnum.CHECKING.getValue());
                operatorContent = "财务审核通过售后单：" + afterSaleCode;
            }
        }

        //如果为审核不通过，则更新售后单状态为驳回
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus)) {
            entity.setAfterSaleStatus(VenAfterSaleStatusEnum.BACKED.getValue());
            entity.setRefusUser(userInfo.getUserName());
            operatorContent = "财务审核驳回售后单：" + afterSaleCode + ",驳回原因：" + refusReason;
        }
        entity.setModifyUser(userInfo.getUserName());
        entity.setFinanceCheckStatus(checkStatus); //审核状态 2=通过 3=不通过
        entity.setRefusReason(refusReason);   //审核驳回原因
        entity.setUserCode(userCode);
        try {
            int flag = xeVenAfterSaleService.updateByPrimaryKey(entity);
            if (flag > 0) {
                //插入日志信息
                insertMqLog("", afterSaleCode, operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================财务审核售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 售后单审核(已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "batchAfterSales", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse batchAfterSales(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                 BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String afterSaleCode = form.getFormCode();  //售后单号
        int checkStatus = form.getCheckStatus();  //审核状态
        String refusReason = form.getRefusReason();  //驳回原因
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus) && StringUtils.isBlank(refusReason)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        XeVenAfterSaleEntity entity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (VenAfterSaleStatusEnum.PENDING.getValue() != entity.getAfterSaleStatus()) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }
        entity.setModifyUser(userInfo.getUserName());
        entity.setAfterSaleStatus(checkStatus); //审核状态 2=通过 4=不通过
        entity.setRefusReason(refusReason);   //审核驳回原因
        entity.setUserCode(userCode);
        try {
            int flag = xeVenAfterSaleService.updateByPrimaryKey(entity);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.error("================审核售后单异常 ================,{}", e);
            return sendAjaxError();
        }


    }

    /**
     * 插入售后单
     *
     * @author chenjing
     */
    @RequestMapping(value = "insertAfterSale", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse insertAfterSale(@RequestBody @Validated XeVenAfterSaleSubmitForm form,
                                 BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单插入缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }

        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        String orderId = form.getOrderId();
        //订单详细信息
        XeVenOrderInfoEntity xeVenOrderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(orderId, userCode);
        //验证orderid
        if (null == xeVenOrderInfoEntity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (!xeVenOrderInfoEntity.getOrderStatus().equals(VenOrderStatusEnum.SEND.getValue())
                && !xeVenOrderInfoEntity.getOrderStatus().equals(VenOrderStatusEnum.FINISH.getValue())) {
            return sendAjaxError(XeVenAfterSaleMsg.ORDER_STATUS_ERR);
        }
        if (null == form.getList()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //退货相关List
        List<XeVenAfterSaleDetailEntity> rejectList = form.getList();
        if (rejectList.size() == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        Map orderServiceMap = new HashMap();
        orderServiceMap.put("orderId", form.getOrderId());
        orderServiceMap.put("userCode", userCode);

        //获取订单明细信息
        List<XeVenOrderInfoDetailEntity> orderInfoDetailList = xeVenOrderService.getOrderDetailByParam(orderServiceMap);
        //本次退款金额
        BigDecimal refundAmount;
        //根据orderid查询订单明细中每个商品的已退金额和已退数量
        List<XeVenRejectRefundDetailView> afterSaleOrderDetailList = xeVenAfterSaleService.getRefundAndReject(orderServiceMap);
        /**
         //已退款金额  该订单下所有售后单对应的退款单中的退款总额（退款金额）
         BigDecimal reFundedAmount = xeVenOrderReFundService.getRefundEdAmountByOrderId(orderId, userCode);
         **/
        BigDecimal rejectTotalAmount = new BigDecimal(0);
        for (XeVenAfterSaleDetailEntity afterSaleDetailEntity : rejectList) {
            //本次退货数量
            BigDecimal rejectNum = afterSaleDetailEntity.getRejectNum();
            rejectNum = null == rejectNum ? new BigDecimal(0) : rejectNum;
            //本次退货金额
            BigDecimal rejectAmount = afterSaleDetailEntity.getRejectAmount();
            rejectAmount = null == rejectAmount ? new BigDecimal(0) : rejectAmount;
            if (Money.of(rejectNum).compareTo(Money.of(new BigDecimal(0))) == 0
                    && Money.of(rejectAmount).compareTo(Money.of(new BigDecimal(0))) == 0) {
                continue;
            }
            for (XeVenOrderInfoDetailEntity detailEntity : orderInfoDetailList) {
                if (detailEntity.getProSku().equals(afterSaleDetailEntity.getProSku())) {
                    String proSku = detailEntity.getProSku();
                    //实际发货数量
                    BigDecimal realSendNum = detailEntity.getRealSendNum();
                    realSendNum = realSendNum == null ? new BigDecimal(0) : realSendNum;

                    ////已退货数量 查询该订单下的所有售后单的已完成的退货单明细中的该商品的退货数量总和
                    //BigDecimal realRejectNum = rejectDetailService.getCountByOrderIdAndSku(proSku, form.getOrderId());
                    //已退货数量 查询该订单下的所有售后单的售后单明细中的该商品的退货数量总和
                    BigDecimal realRejectNum = new BigDecimal(0);
                    //已退款金额 查询该订单下的所有售后单的售后单明细中的该商品的退款金额总和
                    BigDecimal goodsRealRefundAmount = new BigDecimal(0);
                    if (null != afterSaleOrderDetailList) {
                        for (XeVenRejectRefundDetailView xsd : afterSaleOrderDetailList) {
                            if (proSku.equals(xsd.getProSku())) {
                                realRejectNum = xsd.getRealRejectNum();
                                goodsRealRefundAmount = xsd.getRealRefundAmount();
                                break;
                            }
                        }
                    }
                    realRejectNum = realRejectNum == null ? new BigDecimal(0) : realRejectNum;
                    BigDecimal pro = detailEntity.getProCostPrice();  //商品优惠后价
                    //本次该商品退货金额 如果为退货退款，则应拿退货数量进行计算，如果为仅退款直接取传递进来的值
                    /**
                     * 退款金额=退货量×商品优惠后单价
                     * 商品优惠后单价=单价-商品优惠总额÷购买数量
                     * 商品优惠总额=商品优惠金额+商品特批优惠金额
                     */
                    //本次退货金额= 退货量*(单价-(商品优惠金额+商品特批优惠金额)/购买数量)
                    //本次退货金额= 退货量*商品优惠后价
                    BigDecimal goodsRefundAmount = new BigDecimal(0);
                    if (form.getAfterSaleType().equals(VenAfterSaleTypeEnum.REJECT.getValue())) {
//                            BigDecimal pmtAmount = detailEntity.getPmtAmount();
//                            BigDecimal specialDisamount = detailEntity.getSpecialDisamount();
//                            //商品优惠总额
//                            BigDecimal pmtAllAmount = Money.of(null==pmtAmount?new BigDecimal(0):pmtAmount).plus(null == specialDisamount?new BigDecimal(0):specialDisamount).toStoreDecimal();
//                            BigDecimal purchaseNum = detailEntity.getPurchaseNum();
//                            //商品优惠后单价
//                            BigDecimal price = Money.of(pro).minus(Money.of(pmtAllAmount).divide(null == purchaseNum?new BigDecimal(0):purchaseNum)).toStoreDecimal();

                        goodsRefundAmount = Money.of(rejectNum).multiply(pro).toStoreDecimal();
                        // goodsRefundAmount = Money.of(pro).multiply(rejectNum).toStoreDecimal();
                        //如果为退货退款需验证退货数量
                        //验证可退数量 实发数量-已退数量
                        BigDecimal blanceNum = Money.of(realSendNum).minus(realRejectNum).toStoreDecimal();
                        log.info("本次退货数量：{}，可退数量：{}", rejectNum, blanceNum);
                        log.info("商品优惠后单价：{} 退货金额:{}", pro, goodsRefundAmount);
                        /**
                         * 比较本次退货数量和可退数量
                         */
                        if (rejectNum.compareTo(blanceNum) == 1) {
                            log.error("插入售后单明细异常，本次退货数量大于可退数量");
                            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REJECT_NUM_ERR);
                        }
                        afterSaleDetailEntity.setRejectAmount(goodsRefundAmount);
                    } else if (form.getAfterSaleType().equals(VenAfterSaleTypeEnum.REFUND.getValue())) {
                        goodsRefundAmount = afterSaleDetailEntity.getRejectAmount();
                    }
                    //该商品购买总额
                    BigDecimal goodsAmount = detailEntity.getProPayAmount();
                    //可退金额
                    BigDecimal blanceAmount = Money.of(goodsAmount).minus(goodsRealRefundAmount).toStoreDecimal();
                    /**
                     * 比较本次退货退款金额和可退金额
                     */
                    log.info("本次退款金额：{}，可退金额：{}", goodsRefundAmount, blanceAmount);
                    if (goodsRefundAmount.compareTo(blanceAmount) == 1) {
                        log.error("插入售后单明细异常，本次退款金额大于可退金额");
                        return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_AMOUNT_ERR);
                    }
                    //计算退货金额总和
                    rejectTotalAmount = Money.of(rejectTotalAmount).plus(goodsRefundAmount).toStoreDecimal();
                }
            }
        }
        //赋值给售后单本次退款金额
        refundAmount = rejectTotalAmount;
        /**
         //订单支付金额
         BigDecimal payAmount = xeVenOrderInfoEntity.getPayAmount();
         reFundedAmount = null == reFundedAmount ? new BigDecimal(0) : reFundedAmount;
         //剩余可退金额 = 订单支付金额 - 已退款金额
         BigDecimal balance = Money.of(payAmount).minus(reFundedAmount).toStoreDecimal();

         //验证退款金额
         if (refundAmount.compareTo(balance) == 1) {
         return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_AMOUNT_ERR);
         }
         **/
        //如果本地退款金额总额小于==0 直接返回
        if (Money.of(0).compareTo(Money.of(refundAmount)) >= 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //组装XeVenAfterSaleEntity
        XeVenAfterSaleEntity entity = new XeVenAfterSaleEntity();
        entity.setAfterSalesCode(financeSeqUtil.createAferSaleCode()); //售后单号
        entity.setUserCode(userCode);
        entity.setOrderId(form.getOrderId());
        entity.setAfterSaleSource(VenAfterSaleSourceEnum.ON_LINE.getValue());
        entity.setAfterSaleType(form.getAfterSaleType());
        entity.setAfterSaleStatus(VenAfterSaleStatusEnum.PENDING.getValue());
        entity.setAfterSaleReason(form.getAfterSaleReason());
        entity.setAfterSaleRemark(form.getAfterSaleRemark());
        entity.setRefundAmount(refundAmount);  //退款金额
        entity.setCreateUser(userInfo.getUserName());
        entity.setDelFlag(VenDelEnum.NO.getValue());
        entity.setModifyUser(userInfo.getUserName());
        entity.setStoreId(null == form.getStoreId() ? "" : form.getStoreId());
        entity.setStoreName(null == form.getStoreName() ? "" : form.getStoreName());
        entity.setServiceCheckStatus(VenAfterSaleStatusEnum.PENDING.getValue()); //客服审核状态
        entity.setFinanceCheckStatus(VenAfterSaleStatusEnum.PENDING.getValue()); //财务审核状态
        entity.setPurchaseCheckStatus(VenAfterSaleStatusEnum.PENDING.getValue()); //采购审核状态
        entity.setImgs(form.getImgs());
        try {
            int i = xeVenAfterSaleService.insertAfterSale(entity, rejectList, orderInfoDetailList);
            if (i > 0) {
                String operatorContent = "新建售后单：" + entity.getAfterSalesCode();
                //插入日志信息
                insertMqLog("", entity.getAfterSalesCode(), operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================插入售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 根据售后单号查询售后单详细信息
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryDetailList", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse queryDetailList(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                                 BindingResult result) {
        if (null == form) return sendAjaxError(BASEMessage.PARAM_ERROR);
        if (StringUtils.isBlank(form.getAfterSalesCode())) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        try {
            List<XeVenAfterSaleDetailView> orderDetailList = xeVenAfterSaleService.getOrderDetial(form);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("orderDetailList", orderDetailList);
            map.put("picServer", paramConfig.getImgUrl());
            map.put("picDir", XeConstans.ERP_PRO_PIC_DIR);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================售后单获取订单详细信息异常======================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 售后单批量审核(已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "batchAfterSalesList", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse batchAfterSalesList(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                     BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单批量审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String[] formCodes = form.getFormCodes();
        if (formCodes.length == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        form.setFormCodes(formCodes);
        int checkStatus = form.getCheckStatus();  //审核状态
        String refusReason = form.getRefusReason();  //驳回原因
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        if (VenAfterSaleStatusEnum.BACKED.getValue().equals(checkStatus) && StringUtils.isBlank(refusReason)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        form.setModifyUser(userInfo.getUserName());
        form.setUserCode(userCode);
        try {
            int flag = xeVenAfterSaleService.batchAfterSalesList(form);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.error("================批量审核售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 批量删除售后单 (已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "delAfterSaleList", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse delAfterSaleList(@RequestBody @Validated XeVenAfterSaleDelForm form,
                                  BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单删除审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String[] formCodes = form.getAfterSaleFormCodes();
        if (formCodes.length == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        form.setAfterSaleFormCodes(formCodes);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setModifyUser(userInfo.getUserName());
        form.setUserCode(userCode);
        /**
         * 批量删除售后单时，代码中未作状态验证，在sql中直接筛选掉状态=已审核过的数据
         */
        try {
            int flag = xeVenAfterSaleService.delAfterSaleList(form);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.error("================批量删除售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 根据售后单号查询售后单信息
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryAfterSaleInfo", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse queryAfterSaleInfo(@RequestBody @Validated XeVenAfterSaleDetailForm form) {
        if (null == form || null == form.getAfterSalesCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        try {
            XeVenAfterSaleInfoView view = xeVenAfterSaleService.queryAfterSaleInfo(form);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("XeVenAfterSaleInfoView", view);
            map.put("picServer", paramConfig.getImgUrl());
            map.put("picDir", XeConstans.ERP_PRO_PIC_DIR);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================查询售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 编辑售后单
     *
     * @author chenjing
     */
    @RequestMapping(value = "updateAfterSale", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse updateAfterSale(@RequestBody @Validated XeVenAfterSaleSubmitForm form,
                                 BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("售后单编辑缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        if (null == form.getAfterSaleCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }

        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        String orderId = form.getOrderId();
        String afterSaleCode = form.getAfterSaleCode();
        //查询售后单是否存在
        XeVenAfterSaleEntity afterSaleEntity = xeVenAfterSaleService.selectByPrimaryKey(afterSaleCode, userCode);
        if (null == afterSaleEntity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //验证售后单状态是否是已驳回或者待审核
        if (!VenAfterSaleStatusEnum.BACKED.getValue().equals(afterSaleEntity.getAfterSaleStatus())
                && !VenAfterSaleStatusEnum.PENDING.getValue().equals(afterSaleEntity.getAfterSaleStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_STATUS_ERR);
        }
        //订单详细信息
        XeVenOrderInfoEntity xeVenOrderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(orderId, userCode);
        //验证orderid
        if (null == xeVenOrderInfoEntity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (!xeVenOrderInfoEntity.getOrderStatus().equals(VenOrderStatusEnum.SEND.getValue())
                && !xeVenOrderInfoEntity.getOrderStatus().equals(VenOrderStatusEnum.FINISH.getValue())) {
            return sendAjaxError(XeVenAfterSaleMsg.ORDER_STATUS_ERR);
        }
        if (null == form.getList()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //退货相关List
        List<XeVenAfterSaleDetailEntity> rejectList = form.getList();
        if (rejectList.size() == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        Map orderServiceMap = new HashMap();
        orderServiceMap.put("orderId", form.getOrderId());
        orderServiceMap.put("userCode", userCode);
        orderServiceMap.put("afterSaleCode", afterSaleCode);

        //获取订单明细信息
        List<XeVenOrderInfoDetailEntity> orderInfoDetailList = xeVenOrderService.getOrderDetailByParam(orderServiceMap);
        //本次退款金额
        BigDecimal refundAmount;
        //根据orderid查询订单明细中每个商品的已退金额和已退数量
        List<XeVenRejectRefundDetailView> afterSaleOrderDetailList = xeVenAfterSaleService.getRefundAndReject(orderServiceMap);
        /**
         //已退款金额  该订单下所有售后单对应的退款单中的退款总额（退款金额）
         BigDecimal reFundedAmount = xeVenOrderReFundService.getRefundEdAmountByOrderId(orderId, userCode);
         **/
        BigDecimal rejectTotalAmount = new BigDecimal(0);
        for (XeVenAfterSaleDetailEntity afterSaleDetailEntity : rejectList) {
            for (XeVenOrderInfoDetailEntity detailEntity : orderInfoDetailList) {
                if (detailEntity.getProSku().equals(afterSaleDetailEntity.getProSku())) {
                    String proSku = detailEntity.getProSku();
                    //实际发货数量
                    BigDecimal realSendNum = detailEntity.getRealSendNum();
                    realSendNum = realSendNum == null ? new BigDecimal(0) : realSendNum;
                    //本次退货数量
                    BigDecimal rejectNum = afterSaleDetailEntity.getRejectNum();
                    ////已退货数量 查询该订单下的所有售后单的已完成的退货单明细中的该商品的退货数量总和
                    //BigDecimal realRejectNum = rejectDetailService.getCountByOrderIdAndSku(proSku, form.getOrderId());
                    //已退货数量 查询该订单下的所有售后单的售后单明细中的该商品的退货数量总和
                    BigDecimal realRejectNum = new BigDecimal(0);
                    //已退款金额 查询该订单下的所有售后单的售后单明细中的该商品的退款金额总和
                    BigDecimal goodsRealRefundAmount = new BigDecimal(0);
                    if (null != afterSaleOrderDetailList) {
                        for (XeVenRejectRefundDetailView xsd : afterSaleOrderDetailList) {
                            if (proSku.equals(xsd.getProSku())) {
                                realRejectNum = xsd.getRealRejectNum();
                                goodsRealRefundAmount = xsd.getRealRefundAmount();
                                break;
                            }
                        }
                    }
                    realRejectNum = realRejectNum == null ? new BigDecimal(0) : realRejectNum;
                    BigDecimal pro = detailEntity.getProCostPrice();  //商品成交价
                    //本次该商品退货金额 如果为退货退款，则应拿退货数量进行计算，如果为仅退款直接取传递进来的值
                    BigDecimal goodsRefundAmount = new BigDecimal(0);
                    if (form.getAfterSaleType().equals(VenAfterSaleTypeEnum.REJECT.getValue())) {
                        goodsRefundAmount = Money.of(pro).multiply(rejectNum).toStoreDecimal();
                        //如果为退货退款需验证退货数量
                        //验证可退数量 实发数量-已退数量
                        BigDecimal blanceNum = Money.of(realSendNum).minus(realRejectNum).toStoreDecimal();
                        log.info("本次退货数量：{}，可退数量：{}", rejectNum, blanceNum);
                        /**
                         * 比较本次退货数量和可退数量
                         */
                        if (rejectNum.compareTo(blanceNum) == 1) {
                            log.error("编辑售后单明细异常，本次退货数量大于可退数量");
                            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REJECT_NUM_ERR);
                        }
                        afterSaleDetailEntity.setRejectAmount(goodsRefundAmount);
                    } else if (form.getAfterSaleType().equals(VenAfterSaleTypeEnum.REFUND.getValue())) {
                        goodsRefundAmount = afterSaleDetailEntity.getRejectAmount();
                    }
                    //该商品购买总额
                    BigDecimal goodsAmount = detailEntity.getProPayAmount();
                    //可退金额
                    BigDecimal blanceAmount = Money.of(goodsAmount).minus(goodsRealRefundAmount).toStoreDecimal();
                    /**
                     * 比较本次退货退款金额和可退金额
                     */
                    if (goodsRefundAmount.compareTo(blanceAmount) == 1) {
                        log.error("编辑售后单明细异常，本次退款金额大于可退金额");
                        return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_AMOUNT_ERR);
                    }
                    //计算退货金额总和
                    rejectTotalAmount = Money.of(rejectTotalAmount).plus(goodsRefundAmount).toStoreDecimal();
                }
            }
        }
        //赋值给售后单本次退款金额
        refundAmount = rejectTotalAmount;
        //组装XeVenAfterSaleEntity
        afterSaleEntity.setUserCode(userCode);
        afterSaleEntity.setOrderId(form.getOrderId());
        afterSaleEntity.setAfterSaleSource(VenAfterSaleSourceEnum.ON_LINE.getValue());
        afterSaleEntity.setAfterSaleType(form.getAfterSaleType());
        afterSaleEntity.setAfterSaleStatus(VenAfterSaleStatusEnum.PENDING.getValue());
        afterSaleEntity.setAfterSaleReason(form.getAfterSaleReason());
        afterSaleEntity.setAfterSaleRemark(form.getAfterSaleRemark());
        afterSaleEntity.setRefundAmount(refundAmount);  //退款金额
        afterSaleEntity.setDelFlag(VenDelEnum.NO.getValue());
        afterSaleEntity.setModifyUser(userInfo.getUserName());
        afterSaleEntity.setStoreId(form.getStoreId());
        afterSaleEntity.setStoreName(form.getStoreName());
        afterSaleEntity.setServiceCheckStatus(VenAfterSaleStatusEnum.PENDING.getValue()); //客服审核状态
        afterSaleEntity.setFinanceCheckStatus(VenAfterSaleStatusEnum.PENDING.getValue()); //财务审核状态
        afterSaleEntity.setPurchaseCheckStatus(VenAfterSaleStatusEnum.PENDING.getValue()); //采购审核状态
        afterSaleEntity.setImgs(form.getImgs());
        try {
            int i = xeVenAfterSaleService.updateAfterSale(afterSaleEntity, rejectList, orderInfoDetailList);
            if (i > 0) {
                String operatorContent = "编辑售后单：" + afterSaleCode + ",修改内容：" + ToStringBuilder.reflectionToString(form);
                //插入日志信息
                insertMqLog("", afterSaleCode, operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================插入售后单异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 查询订单列表
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryOrderListForAfterSale", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse queryOrderListForAfterSale(@RequestBody XeVenAfterSaleOrderQueryForm form) {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        if (null == form) {
            form = new XeVenAfterSaleOrderQueryForm();
        }
        form.setUserCode(userInfo.getUserCode());
        if (StringUtils.isNotBlank(form.getFormIdType())) {
            int formIdType = Integer.parseInt(form.getFormIdType());
            switch (formIdType) {
                case 1:   //订单编号
                    form.setOrderId(form.getFormIdValue());
                    break;
                case 2:   //支付单号,
                    form.setPayNumber(form.getFormIdValue());
                    break;
                case 3:   //商品名称
                    form.setProName(form.getFormIdValue());
                    break;
                case 4:   //商品货号
                    form.setProName(form.getFormIdValue());
                    break;
                case 5:   //客户账号
                    form.setLoginAccount(form.getFormIdValue());
                    break;
                case 6:   // 收货人
                    form.setCaConsignee(form.getFormIdValue());
                    break;
                default:
                    break;
            }

        }
        String startTime = form.getStartDate();
        String endTime = form.getEndDate();
        //设定查询中日期为3个月以内
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            Boolean dateCm = DateUtil.comparableTime(startTime, endTime);
            if (!dateCm) {
                return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_DATE_COMPARABLE);
            }
        }
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)) {
            endTime = DateUtil.getDate(new Date());
            ;
            startTime = DateUtil.strToNMonth(endTime, -3);
        }
        if (StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = DateUtil.strToNMonth(endTime, -3);
        }
        if (StringUtils.isBlank(endTime) && StringUtils.isNotBlank(startTime)) {
            endTime = DateUtil.strToNMonth(startTime, 3);
        }
        int timeType = Integer.parseInt(form.getFormTimeType());
        switch (timeType) {
            case 1: //下单时间
                form.setStartCreateDate(startTime);
                form.setEndCreateDate(endTime);
                break;
            case 2: //付款时间
                form.setStartPayTime(startTime);
                form.setEndPayTime(endTime);
                break;
            case 3: //发货时间
                form.setStartSendTime(startTime);
                form.setEndSendTime(endTime);
                break;
            default:
                break;
        }
        XePageInfo<XeVenAfterSaleOrderView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        try {
            //售后单列表
            List<XeVenAfterSaleOrderView> afterSaleOrderList = xeVenAfterSaleService.queryAfterSaleOrderList(form);
            xePageInfo = new XePageInfo<>(afterSaleOrderList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("afterSaleOrderList", afterSaleOrderList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================查询订单列表异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 根据订单号查询订单详细信息
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryOrderDetailList", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResponse queryOrderDetailList(@RequestBody @Validated XeVenAfterSaleDetailForm form) {
        if (null == form || null == form.getOrderId()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        try {
            Long afterCount = xeVenAfterSaleService.selectAfterSaleByOrderId(form.getOrderId());
            Map<String, Object> map = new HashMap<String, Object>();
            if (afterCount > 0) {
                map.put("canprompt", "当前订单下存在处理中的售后单，请确认后提交！");
            }
            List<XeVenAfterSaleDetailView> view = xeVenAfterSaleService.queryOrderInfoDetail(form);
            map.put("XeVenAfterSaleInfoList", view);
            map.put("picServer", paramConfig.getImgUrl());
            map.put("picDir", XeConstans.ERP_PRO_PIC_DIR);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================查询订单详细信息异常 ================,{}", e);
            return sendAjaxError();
        }
    }


    /**
     * 统一日志信息
     *
     * @author chenjing
     */
    private void insertMqLog(String logType, String key, String operatorContent) {
        try {
            String ipAddress = RequestUtil.getClientIpAddress(request);
            if (StringUtils.isBlank(logType)) {
                logType = ErpLogTypeEnum.erpAfterSale.getValue();
            }
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            String userCode = userInfo.getUserCode();
            OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, key, logType, userInfo.getUserName(), operatorContent, userCode);
        } catch (Exception e) {
            log.error("售后单相关MQ日志插入失败,logType={},operatorContent={}", logType, operatorContent);
        }
    }
}
